package com.huwaiwai.thread.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程工厂
 * Created by huweiwei on 2017/4/10.
 */
public class NameThreadFactory implements ThreadFactory {
    private AtomicInteger number;
    private String name;
    private boolean daemon;
    public NameThreadFactory (String name, boolean daemon) {
        this.number = new AtomicInteger(0);
        this.name = name;
        this.daemon = daemon;
    }
    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, getThreadName());
        thread.setDaemon(daemon);
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }
    private String getThreadName() {
        return new StringBuffer(name).append("-").append(number.incrementAndGet()).toString();
    }
}
